<template>
  <div>
    <van-nav-bar
        :title="receive.name"
        left-arrow
        @click-left="goBack()"
    />

    <div class="dialog-wrap" id="scrollContainer">
      <van-pull-refresh v-model="page.refresh" @refresh="onRefresh()">
        <div id="scrollEnd">

          <mu-flex class="dialog-list" :justify-content="item.isSend ? 'end' : 'start'"
                   v-for="(item, index) in messages" :key="index">

            <mu-flex v-if="!item.isSend" :class="'dialog-left'">
              <mu-flex justify-content="end">
                <mu-avatar>
                  <img :src="item.img"/>
                </mu-avatar>
              </mu-flex>
              <mu-flex justify-content="start">
                <mu-flex>
                  <span>{{ item.message }}</span>
                </mu-flex>
              </mu-flex>
            </mu-flex>

            <mu-flex v-else :class="'dialog-right'">
              <mu-flex>
                <mu-flex class="flex-wrapper">
                  <span>{{ item.message }}</span>
                </mu-flex>
              </mu-flex>
              <mu-flex>
                <mu-avatar>
                  <img :src="item.img"/>
                </mu-avatar>
              </mu-flex>
            </mu-flex>

          </mu-flex>
        </div>
      </van-pull-refresh>
    </div>

    <div class="chat-bottom">
      <input v-model="value" type="text" ref="message" @keydown.enter="sendMessage()"/>
      <mu-button color="primary" @click="sendMessage">发送</mu-button>
    </div>


  </div>
</template>

<script>
import {Toast} from "vant";

export default {
  data() {
    return {
      value: "",
      receive: {
        name: "",
        id: "",
        img: ""
      },
      send: {
        name: "",
        id: "",
        img: ""
      },
      page: {
        refresh: false,
        current: 1,
        pages: 0
      },
      messages: [{
        isSend: false,
        img: "",
        message: "",
      }],
    }
  },
  mounted() {
    this.messages = [];
    this.receive.id = this.$route.query.id;
    this.onload();
  },
  methods: {
    onRefresh() {
      setTimeout(() => {
        Toast("刷新成功");
        this.page.refresh = false;
        if (this.page.current <= this.page.pages) {
          this.pageMessage(this.page.current);
          this.page.current++;
        }
      }, 1000);
    },
    goBack() {
      this.close();
      this.$router.go(-1);
    },
    pageMessage(current, isPush) {
      this.http
          .post("/api/zyx/message/page", {
            currentPage: current,
            pageSize: 10,
            userId: this.receive.id,
          })
          .then((res) => {
            // 请求到数据存放到本地
            this.page.pages = res.data.data.pages;
            for (let i in res.data.data.records) {
              this.messages.unshift({
                isSend: (res.data.data.records[i].receiveId === this.receive.id),
                img: (res.data.data.records[i].receiveId === this.receive.id ? this.send.img : this.receive.img),
                message: res.data.data.records[i].text,
              });
            }
          });
    },
    onload() {
      this.http
          .get("/api/zyx/user/detail" + "?userId=" + this.receive.id)
          .then((res) => {
            this.receive.name = res.data.data.name;
            this.receive.img = res.data.data.profileImg;
            this.http
                .get("/api/zyx/user/detail" + "?userId=")
                .then((res) => {
                  this.send.id = res.data.data.id;
                  this.send.name = res.data.data.name;
                  this.send.img = res.data.data.profileImg;
                  this.init();
                });
          });
    },
    init() {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(`ws://162.14.99.105:8082/message/${this.send.id}/${this.receive.id}`)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open() {
      console.log("socket连接成功")
      this.messages = [];
      this.page.current = 1;
      this.pageMessage(this.page.current);
      this.page.current++;
    },
    error() {
      console.log("连接错误")
    },
    getMessage(msg) {
      this.messages.push({
        isSend: false,
        img: this.receive.img,
        message: JSON.parse(msg.data).text,
      });
      this.scrollToEnd();
    },
    sendMessage() {
      if(this.value === "") {
        Toast("请输入消息");
      } else{
        this.socket.send(this.value);
        this.messages.push({
          isSend: true,
          img: this.send.img,
          message: this.value,
        });
        this.value = "";
        this.scrollToEnd();
      }
    },
    close() {
      this.socket.close(1000, "CLOSED NORMALLY");
      console.log("socket已经关闭")
    },
    scrollToEnd() {
      this.$nextTick(()=>{
        document.getElementById("scrollContainer").scrollTop = document.getElementById("scrollEnd").lastElementChild.offsetTop;
      });
    },
  },
}
</script>

<style lang="scss" scoped>
.chat-bottom {
  padding: 0.5rem;
  position: absolute;
  bottom: 0;
  width: 100%;
  background: #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

input {
  height: 2.3rem;
  display: inline-block;
  width: 100%;
  /*padding: 0.5rem;*/
  border: none;
  border-radius: 0.2rem;
  font-size: 1rem;
  margin-right: 0.5rem;
}

.dialog-wrap {
  padding: 0.5rem;
  overflow-y: auto;
  height: 85vh;

  .dialog-list {
    margin-top: 0.5rem;

    .dialog-left {

      span {
        background-color: #42b983;
        margin: 0.3rem;
        border-radius: 1rem;
        padding: 0.5rem;
      }

    }

    .dialog-right {

      span {
        background-color: #e0e0e0;
        margin: 0.3rem;
        border-radius: 1rem;
        padding: 0.5rem;
      }

    }
  }
}
</style>